<?php

use Mapper\OrderModel as OrderMapper;
use Mapper\OrderRefundModel as RefundMapper;
use Mapper\MemberModel as MemberMapper;
use Mapper\SparringbuysModel as BuyMapper;
use Mapper\SparringbuydetailModel as BuyDetailMapper;
use Mapper\SparringsellModel as SellMapper;
use Mapper\ComplaintModel as ComplaintMapper;
use Mapper\SparringgameModel as GameMapper;

class OrderController extends \Base\ApiController {

    public $statusToWord = [
        1 => '待支付',
        2 => '已支付',
        3 => '退款中',
        4 => '拒绝退款',
        5 => '已退款',
        6 => '已完成',
        7 => '已评价',
        8 => '已关闭',
    ];

    /**
     * @desc 添加订单信息
     *
     * @return false
     */
    public function addAction() {
        $request    = $this->getRequest();
        $fromUid    = (int)$request->get('from_uid');
        $toUid      = $this->uid();
        $price      = (float)$request->get('price', 0.00);
        $payPrice   = (float)$request->get('pay_price', 0.00);
        $type       = (int)$request->get('type', 1);
        $sparringNo = (string)$request->get('sparring_no');
        $envelopeId = (int)$request->get('envelope_id'); //暂时不使用
        $duration   = (int)$request->get('duration');
        $remark     = (string)trim($request->get('remark'));

        if($fromUid < 65535 || $fromUid === $toUid) {
            return $this->response(null, false, 10601, '无效的uid');
        }

        if($price <= 0) {
            return $this->response(null, false, 10602, '原价价格有误');
        }

        if($payPrice <= 0) {
            return $this->response(null, false, 10603, '支付价格有误');
        }

        $memberMapper = MemberMapper::getInstance();
        $fromUidModel = $memberMapper->findById($fromUid);
        $toUidModel   = $memberMapper->findById($toUid);

        if(!$fromUidModel instanceof \MemberModel || !$toUidModel instanceof \MemberModel) {
            return $this->response(null, false, 10601, '无效的uid');
        }

        if($type === \Lib\Consts::ORDER_TYPE_SPARRING_BUY) {
            $buyDetailMapper = BuyDetailMapper::getInstance();
            $sparringNoArr   = $sparringNo;

            if(strpos($sparringNo, ',') !== false) {
                $sparringNoArr = explode(',', $sparringNo);
            }

            $buyDetailModels = $buyDetailMapper->fetchAll(['id' => $sparringNoArr]);

            if(empty($buyDetailModels)) {
                return $this->response(null, false, 10604, '看大腿id信息有误');
            }

            foreach($buyDetailModels as $buyDetailModel) {
                if($buyDetailModel->getBegin_time() < time()) {
                    return $this->response(null, false, 10621, '包含过期陪练时段, 请重新下单');
                }

                if($buyDetailModel->getStatus() !== \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL) {
                    return $this->response(null, false, 10620, '陪练已被他人抢购, 请重新下单');
                }
            }

            $data = [
                'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
            ];

            try {
                $rows = $buyDetailMapper->update($data, [
                    'id'             => $sparringNoArr,
                    'status'         => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
                    'begin_time > ?' => time(),
                ]);

                if($rows <= 0) {
                    return $this->response(null, false, 10605, '看大腿状态更新失败');
                }
            } catch(\Exception $exc) {
                return $this->response(null, false, 10100, '异常信息报错');
            }
        } elseif($type === \Lib\Consts::ORDER_TYPE_SPARRING_SELL) {
            if($duration <= 0) {
                return $this->response(null, false, 10315, '无效的时长');
            }

            $sellMapper = SellMapper::getInstance();
            $sellModel  = $sellMapper->findById($sparringNo);

            if(!$sellModel instanceof \SparringSellModel) {
                return $this->response(null, false, 10622, '无效的求大腿id');
            }

            $data = [
                'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
            ];

            try {
                $rows = $sellMapper->update($data, [
                    'id'     => $sparringNo,
                    'status' => \Lib\Consts::SPARRING_SELL_STATUS_NORMAL,
                ]);

                if($rows <= 0) {
                    return $this->response(null, false, 10606, '求大腿状态更新失败');
                }
            } catch(\Exception $exc) {
                return $this->response(null, false, 10100, '异常信息报错');
            }
        }

        $orderMapper = OrderMapper::getInstance();
        $orderNo     = $this->createOrderNo();

        $model = new \OrderModel();
        $model->setFrom_uid($fromUid);
        $model->setTo_uid($toUid);
        $model->setPrice($price);
        $model->setPay_price($payPrice);
        $model->setType($type);
        $model->setStatus(\Lib\Consts::ORDER_STATUS_NOPAY);
        $model->setOrder_no($orderNo);
        $model->setEnvelope_id($envelopeId);
        $model->setSparring_no($sparringNo);
        $model->setAdd_time(time());
        $model->setDuration($duration);
        $model->setRemark($remark);

        try {
            $id = $orderMapper->insert($model);

            if($id > 0) {
                $tmpData = [
                    'add_time' => date('Y年m月d日 H:s'),
                    'order_no' => $orderNo,
                ];

                \Lib\Queue::push('wxmsg', [
                    'touser'      => $fromUidModel->getOpen_id(),
                    'template_id' => \Lib\Consts::TEMP_ID_NO_PAY,
                    'url'         => 'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $id . '&fund_flow=1',
                    'data'        => \Lib\Wechat::getInstance()->getTmp(\Lib\Consts::TEMP_ID_NO_PAY, $tmpData),
                ]);

                return $this->response(['order_id' => $id]);
            }

            return $this->response(null, false, 10607, '创建订单失败');
        } catch(\Exception $exc) {
            return $this->response(null, false, 10100, '异常信息报错');
        }
    }

    /**
     * @desc 订单号生成
     *
     * @return string
     */
    public function createOrderNo() {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
     * @desc 更改订单状态
     * @todo 订单状态判断
     * @return false
     */
    public function chgstatusAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');

        if($orderId <= 0) {
            return $this->response(null, false, 10608, '订单id有误');
        }

        if(!isset($this->statusToWord[$status])) {
            return $this->response(null, false, 10609, '订单状态值有误');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, 10610, '无效的订单id');
        }

        $orderModel->setStatus($status);

        try {
            $rows = $orderMapper->update($orderModel, ['id' => $orderId]);
            return $rows > 0 ? $this->response(null) : $this->response(null, false, 10611, '订单状态变更失败');
        } catch(\Exception $e) {
            return $this->response(null, false, 10100, '异常信息报错');
        }
    }

    /**
     * @desc 订单列表(支出)
     *
     * @return false
     */
    public function outlistAction() {
        $this->close();
        $this->confirm();
        $uid         = $this->uid();
        $return      = [];
        $request     = $this->getRequest();
        $page        = (int)$request->get('page', 1);
        $perPage     = (int)$request->get('per_page', 15);
        $page        = max(1, $page);
        $perPage     = min(30, $perPage);
        $limit       = $perPage;
        $offset      = $limit * ($page - 1);
        $orderMapper = OrderMapper::getInstance();
        $orderModels = $orderMapper->fetchAll([
            'to_uid'     => $uid,
            'status < ?' => 9,
        ], 'add_time DESC', $limit, $offset);

        if(empty($orderModels)) {
            return $this->response([]);
        }

        $memberMapper = MemberMapper::getInstance();

        foreach($orderModels as $orderModel) {
            $data = $orderModel->toArray();
            $type = (int)$orderModel->getType();

            if($type !== 1) {
                continue;
            }

            $sparringId  = $orderModel->getSparring_no();
            $fromUid     = $orderModel->getFrom_uid();
            $memberModel = $memberMapper->findById($fromUid);

            if(!$memberModel instanceof \MemberModel) {
                return $this->response(null, false, 10612, '无效的uid');
            }

            $data['avatar']      = $memberModel->getAvatar();
            $data['nick_name']   = urldecode($memberModel->getNick_name());
            $data['mobile']      = $memberModel->getMobile();
            $status              = $orderModel->getStatus();
            $data['status_word'] = isset($this->statusToWord[$status]) ? $this->statusToWord[$status] : '';

            if($type === 1) { // 看大腿
                if(strpos($sparringId, ',') !== false) {
                    $sparringId = explode(',', $sparringId);
                }

                $buyDetailMapper = BuyDetailMapper::getInstance();
                $detailModel     = $buyDetailMapper->fetch(['id' => $sparringId], 'begin_time');
                $gameMapper      = GameMapper::getInstance();
                $gameModel       = $gameMapper->findById($detailModel->getGame_id());

                if(!$gameModel instanceof \SparringGameModel) {
                    $data['game_name'] = '';
                } else {
                    $data['game_name'] = $gameModel->getGame_name();
                }

                $data['time_interval'] = date('H:i', $detailModel->getBegin_time()) . '-' .
                    date('H:i', $detailModel->getEnd_time());
                $data['count']         = count($sparringId);
            }

            $date          = date('Y-m-d', $orderModel->getAdd_time());
            $tmp['data'][] = $data;
            $tmp['date']   = $date;

            if(isset($return[$date])) {
                $return[$date]['data'][] = $data;
            } else {
                $return[$date] = $tmp;
            }

            unset($tmp);
        }

        if(!empty($return)) {
            $return = array_values($return);
        }

        return $this->response($return);
    }

    /**
     * @desc 订单收益(收入)
     *
     * @return false
     */
    public function inlistAction() {
        $this->close();
        $this->confirm();
        $uid         = $this->uid();
        $return      = [];
        $request     = $this->getRequest();
        $page        = (int)$request->get('page', 1);
        $perPage     = (int)$request->get('per_page', 15);
        $page        = max(1, $page);
        $perPage     = min(30, $perPage);
        $limit       = $perPage;
        $offset      = $limit * ($page - 1);
        $orderMapper = OrderMapper::getInstance();
        $orderModels = $orderMapper->fetchAll([
            'from_uid' => $uid,
            'status'   => [1, 2, 3, 4, 5, 6],
        ], 'add_time DESC', $limit, $offset);

        if(empty($orderModels)) {
            return $this->response([]);
        }

        $memberMapper = MemberMapper::getInstance();

        foreach($orderModels as $orderModel) {
            $data = $orderModel->toArray();
            $type = (int)$orderModel->getType();

            if($type !== 1) {
                continue;
            }

            $sparringId  = $orderModel->getSparring_no();
            $toUid       = $orderModel->getTo_uid();
            $memberModel = $memberMapper->findById($toUid);

            if(!$memberModel instanceof \MemberModel) {
                return $this->response(null, false, 10612, '无效的uid');
            }

            $buyDetailMapper     = BuyDetailMapper::getInstance();
            $status              = $orderModel->getStatus();
            $data['status_word'] = isset($this->statusToWord[$status]) ? $this->statusToWord[$status] : '';
            $data['avatar']      = $memberModel->getAvatar();
            $data['nick_name']   = urldecode($memberModel->getNick_name());
            $data['mobile']      = $memberModel->getMobile();

            if($type === 1) { // 看大腿
                if(strpos($sparringId, ',') !== false) {
                    $sparringId = explode(',', $sparringId);
                }

                $detailModel = $buyDetailMapper->fetch(['id' => $sparringId], 'begin_time');
                $gameMapper  = GameMapper::getInstance();
                $gameModel   = $gameMapper->findById($detailModel->getGame_id());

                if(!$gameModel instanceof \SparringGameModel) {
                    $data['game_name'] = '';
                } else {
                    $data['game_name'] = $gameModel->getGame_name();
                }

                $data['time_interval'] = date('H:i', $detailModel->getBegin_time()) . '-' .
                    date('H:i', $detailModel->getEnd_time());
                $data['count']         = count($sparringId);

                $date          = date('Y-m-d', $orderModel->getAdd_time());
                $tmp['data'][] = $data;
                $tmp['date']   = $date;

                if(isset($return[$date])) {
                    $return[$date]['data'][] = $data;
                } else {
                    $return[$date] = $tmp;
                }

                unset($tmp);
            }
        }

        if(!empty($return)) {
            $return = array_values($return);
        }

        return $this->response($return);

    }

    /**
     * @desc 订单详情
     *
     * @return false
     */
    public function detailAction() {
        $request  = $this->getRequest();
        $orderId  = (int)$request->get('order_id');
        $fundFlow = (int)$request->get('fund_flow');
        $uid      = 0;

        if($orderId <= 0) {
            return $this->response(null, false, 10608, '订单id有误');
        }

        if($fundFlow !== 1 && $fundFlow !== 2) { //1支出 2收入
            return $this->response(null, false, 50000, '无效的收支状态');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, 10610, '无效的订单ID');
        }

        $data                = $orderModel->toArray();
        $data['order_time']  = date('Y-m-d H:i:s', $orderModel->getAdd_time());
        $status              = $orderModel->getStatus();
        $data['status_word'] = isset($this->statusToWord[$status]) ? $this->statusToWord[$status] : '';

        $memberMapper = MemberMapper::getInstance();

        if((int)$fundFlow === 1) {
            $uid = $orderModel->getFrom_uid();
        } elseif((int)$fundFlow === 2) {
            $uid = $orderModel->getTo_uid();
        }

        $memberModel = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return $this->response(null, false, 10612, '无效的uid');
        }

        $data['avatar']    = $memberModel->getAvatar();
        $data['nick_name'] = urldecode($memberModel->getNick_name());
        $data['uid']       = $memberModel->getId();
        $data['gender']    = $memberModel->getGender();

        $birthday = $memberModel->getBirthday();
        $age      = date('Y') - date('Y', $birthday) - 1;

        if(date('m', time()) == date('m', $birthday)) {
            if(date('d', time()) > date('d', $birthday)) {
                ++$age;
            }
        } elseif(date('m', time()) > date('m', $birthday)) {
            ++$age;
        }

        $data['age'] = $age;

        $sparringId      = explode(',', $orderModel->getSparring_no());
        $buyDetailMapper = BuyDetailMapper::getInstance();
        $gameMapper      = GameMapper::getInstance();
        $detailModels    = $buyDetailMapper->fetchAll(['id' => $sparringId], 'begin_time');

        foreach($detailModels as $detailModel) {
            $data['time_interval'][] = date('H:i', $detailModel->getBegin_time()) . '-' .
                date('H:i', $detailModel->getEnd_time());
        }

        $gameModel = $gameMapper->findById($detailModels[0]->getGame_id());

        if(!$gameModel instanceof \SparringGameModel) {
            $data['game_name'] = '';
        } else {
            $data['game_name'] = $gameModel->getGame_name();
        }

        $data['count'] = count($sparringId);

        return $this->response($data);
    }

    /**
     * @desc 提交申诉
     *
     * @todo 判断何种状态不能进行申诉
     * @return false
     */
    public function addcomplaintAction() {
        $request = $this->getRequest();
        $content = (string)trim($request->get('content'));
        $orderId = (int)$request->get('order_id');

        if($orderId <= 0) {
            return $this->response(null, false, 10702, '订单id有误');
        }

        if(empty($content)) {
            return $this->response(null, false, 10704, '内容不能为空');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, 10703, '无效的订单id');
        }

        $mapper = ComplaintMapper::getInstance();

        $model = new \ComplaintModel();
        $model->setContent($content);
        $model->setOrder_id($orderId);
        $model->setAdd_time(time());
        $model->setImg_url('');
        $model->setStatus(1);

        try {
            $id = $mapper->insert($model);
            return $id > 0 ? $this->response(null) : $this->response(null, false, '申诉提交失败', 10619);
        } catch(\Exception $exc) {
            return $this->response(null, false, 10100, '异常信息报错');
        }
    }

    public function complaintnameAction() {
        $request      = $this->getRequest();
        $cUid         = (int)$request->get('c_uid');
        $uid          = $this->uid();
        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);
        $name         = urldecode($memberModel->getNick_name());

        $cMemberModel = $memberMapper->findById($cUid);

        if(!$cMemberModel instanceof \MemberModel) {
            return $this->response(null, false, 50000, '无效的uid');
        }

        $cName = urldecode($cMemberModel->getNick_name());

        return $this->response(['name' => $name, 'c_name' => $cName]);
    }

    /**
     * @desc 下单前
     *
     * @return false
     */
    public function orderinfo22Action() {
        $request    = $this->getRequest();
        $sparringId = (int)$request->get('sparring_id');
        $uid        = $this->uid();
        $type       = (int)$request->get('type', 1);

        if($type !== 1) {
            return $this->response(null, false, 10710, '无效的类型');
        }

        if($sparringId <= 0) {
            return $this->response(null, false, 10705, '无效的陪练信息id');
        }

        $memberMapper = MemberMapper::getInstance();

        if($type === 1) {
            $buyMapper = BuyMapper::getInstance();
            $buyModel  = $buyMapper->findById($sparringId);

            if(!$buyModel instanceof \SparringBuysModel) {
                return $this->response(null, false, 10708, '无效的看大腿id');
            }

            $buyDetailMapper = BuyDetailMapper::getInstance();
            $detailModel     = $buyDetailMapper->fetch([
                'sparring_buy_id' => $sparringId,
                'status'          => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
            ]);

            if(!$detailModel instanceof \SparringBuyDetailModel) {
                return $this->response(null, false, 10705, '无效的看大腿id');
            }

            $publisherUid = $buyModel->getUid();

            $return                  = $detailModel->toArray();
            $return['time_interval'] = date('H:i', $detailModel->getBegin_time()) . '-' . date('H:i', $detailModel->getEnd_time());
            $return['can_order']     = ($publisherUid !== $uid ? '1' : '0');
        }

        $publisherMemberModel = $memberMapper->findById($publisherUid);

        if(!$publisherMemberModel instanceof \MemberModel) {
            return $this->response(null, false, 10707, '无效的uid');
        }

        $return['publisher_nickname'] = urldecode($publisherMemberModel->getNick_name());
        $return['publisher_gender']   = $publisherMemberModel->getGender();
        $return['publisher_avatar']   = $publisherMemberModel->getAvatar();
        $memberModel                  = $memberMapper->findById($uid);
        $return['own_avatar']         = $memberModel->getAvatar();

        return $this->response($return);
    }

    /**
     * @desc 更改订单状态
     *
     * @param $orderId
     * @param $status
     * @return false
     */
    protected function changestatus($orderId, $oldStatus, $newStatus) {
        if($orderId <= 0) {
            return $this->response(null, false, 50000, '订单id有误');
        }

        if($oldStatus <= 0 || $oldStatus >= 10 || $newStatus <= 0 || $newStatus >= 10) {
            return $this->response(null, false, 50000, '订单状态值有误');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, 50000, '无效的订单id');
        }

        if($orderModel->getStatus() !== $oldStatus) {
            return $this->response(null, false, 50000, '订单不能关闭');
        }

        $data = [
            'status'      => $newStatus,
            'update_time' => time(),
        ];

        try {
            $rows = $orderMapper->update($data, ['id' => $orderId, 'status' => $oldStatus]);
            return $rows > 0 ? true : false;
        } catch(\Exception $e) {
            return false;
        }
    }

    /**
     * @desc 关闭订单
     *
     * @return false
     */
    public function closeAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');

        if($status !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            return $this->response(null, false, 50000, '订单不能关闭');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderMapper->begin();

        $orderModel = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, 50000, '无效的订单id');
        }

        if($orderModel->getStatus() !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            return $this->response(null, false, 50000, '订单不能关闭');
        }

        $sparringNo      = $orderModel->getSparring_no();
        $sparringNoArr   = explode(',', $sparringNo);
        $buyDetailMapper = BuyDetailMapper::getInstance();

        $data = [
            'status'      => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
            'update_time' => time(),
        ];

        try {
            $rows = $buyDetailMapper->update($data, [
                'id'     => $sparringNoArr,
                'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
            ]);
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            $orderMapper->rollback();
            $this->response(null, false, 50000, '还原看大腿信息失败');
        }

        $return = $this->changestatus($orderId, \Lib\Consts::ORDER_STATUS_NOPAY, \Lib\Consts::ORDER_STATUS_CLOSE);

        if(!$return) {
            $orderMapper->rollback();
            $this->response(null, false, 10641, '关闭订单失败');
        }

        $orderMapper->commit();
        return \Response::data(null);
    }

    /**
     * @desc 退款(卖家/大腿)
     *
     * @return false
     */
    public function refundAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');
        $uid     = $this->uid();

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, 50000, '无效的订单id');
        }

        if($orderModel->getFrom_uid() !== $uid) {
            return $this->response(null, false, 50000, '只有卖家能退款');
        }

        if($status !== \Lib\Consts::ORDER_STATUS_PAY) {
            return $this->response(null, false, 50000, '订单不能退款');
        }
        $refundMapper = RefundMapper::getInstance();

        $return = \Lib\Finance::getInstance()->flow($orderModel->getTo_uid(), \Lib\Consts::F_REFUND_SUCCESS,
            $orderModel->getPay_price(), function () use ($orderModel, $refundMapper) {

                $return = $this->changestatus($orderModel->getId(), \Lib\Consts::ORDER_STATUS_PAY,
                    \Lib\Consts::ORDER_STATUS_REFUND_FINISH);

                if(!$return) {
                    return false;
                }

                $model = new \OrderRefundModel();
                $model->setOrder_id($orderModel->getId());
                $model->setSum($orderModel->getPrice());
                $model->setReason('');
                $model->setStatus(\Lib\Consts::ORDER_REFUND_STATUS_SUCCESS);
                $model->setAdd_time(time());

                $id = $refundMapper->insert($model);

                if($id <= 0) {
                    return false;
                }

                $sparringNoArr   = explode(',', $orderModel->getSparring_no());
                $buyDetailMapper = BuyDetailMapper::getInstance();

                $data = [
                    'status'      => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
                    'update_time' => time(),
                ];

                try {
                    $rows = $buyDetailMapper->update($data, [
                        'id'     => $sparringNoArr,
                        'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
                    ]);
                } catch(\Exception $e) {
                    $rows = 0;
                }

                if($rows <= 0) {
                    return false;
                }

                return true;
            });

        if(!$return) {
            return $this->response(null, false, 50001, '订单退款失败');
        }

        $buyDetailMapper = BuyDetailMapper::getInstance();
        $sparringNoArr   = explode(',', $orderModel->getSparring_no());
        $detailModels    = $buyDetailMapper->fetchAll(['id' => $sparringNoArr]);

        if(empty($detailModels)) {
            return false;
        }

        $timeInterval = '';

        foreach($detailModels as $detailModel) {
            $timeInterval .=
                date('H:i', $detailModel->getBegin_time()) . '-' . date('H:i', $detailModel->getEnd_time()) . ' ';
        }

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($orderModel->getTo_uid());

        if(!$memberModel instanceof \MemberModel) {
            return $this->response(null);
        }

        $data = [
            'order_no'    => $orderModel->getOrder_no(),
            'time'        => $timeInterval,
            'cancel_time' => date('m月d日 H:i', time()),
            'price'       => $orderModel->getPrice(),
        ];

        \Lib\Queue::push('wxmsg', [
            'touser'      => $memberModel->getOpen_id(),
            'template_id' => \Lib\Consts::TEMP_ID_REFUND,
            'url'         => 'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $orderId . '&fund_flow=1',
            'data'        => \Lib\Wechat::getInstance()->getTmp(\Lib\Consts::TEMP_ID_REFUND, $data),
        ]);

        return $this->response(null);
    }

    public function agreerefundAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');

        $refundMapper = RefundMapper::getInstance();
        $refundModel  = $refundMapper->findByOrder_id($orderId);

        if(!$refundModel instanceof \OrderRefundModel) {
            $this->response(null, false, 50000, '退款不存在');
        }

        if($refundModel->getStatus() === \Lib\Consts::ORDER_REFUND_STATUS_REPLY) {
            $this->response(null, false, 50000, '退款状态有误');
        }

        $data = [
            'status'      => \Lib\Consts::ORDER_REFUND_STATUS_SUCCESS,
            'update_time' => time(),
        ];

        $refundMapper->begin();

        try {
            $rows = $refundMapper->update($data, [
                'order_id' => $orderId,
                'status'   => \Lib\Consts::ORDER_REFUND_STATUS_REPLY,
            ]);
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            $refundMapper->rollback();
            $this->response(null, false, 50000, '同意退款申请失败');
        }

        $return = $this->changestatus($orderId, \Lib\Consts::ORDER_STATUS_REFUNDING,
            \Lib\Consts::ORDER_STATUS_REFUND_FINISH);

        if(!$return) {
            $refundMapper->rollback();
            $this->response(null, false, 50000, '同意退款申请失败');
        }

        $refundMapper->commit();
        return $this->response(null);
    }

    public function confirmAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');

        if($orderId <= 0) {
            return $this->response(null, false, 50000, '无效的订单id');
        }

        if($status !== \Lib\Consts::ORDER_STATUS_PAY && $status !== \Lib\Consts::ORDER_STATUS_REFUND_REFUSE) {
            return $this->response(null, false, 50000, '不能确认收货');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, 50000, '无效的订单id');
        }

        if($orderModel->getStatus() !== \Lib\Consts::ORDER_STATUS_PAY &&
            $orderModel->getStatus() !== \Lib\Consts::ORDER_STATUS_REFUND_REFUSE
        ) {
            return $this->response(null, false, 50000, '不能确认收货');
        }

        $return = \Lib\Finance::getInstance()->flow($orderModel->getFrom_uid(), \Lib\Consts::F_ORDER_INCOME,
            $orderModel->getPay_price(), function () use ($orderModel, $orderMapper) {
                $return = \Lib\Finance::getInstance()->commission($orderModel->getFrom_uid(),
                    $orderModel->getPay_price() * \Lib\Consts::COMMISSION_RATE);

                if(!$return) {
                    return false;
                }

                $isSuccess = $this->changestatus($orderModel->getId(), $orderModel->getStatus(),
                    \Lib\Consts::ORDER_STATUS_FINISH);

                return $isSuccess;
            });

        if(!$return) {
            return $this->response(null, false, 50000, '确认订单失败');
        }

        $memberMapper    = MemberMapper::getInstance();
        $buyMemberModel  = $memberMapper->findById($orderModel->getTo_uid());
        $sellMemberModel = $memberMapper->findById($orderModel->getFrom_uid());

        $sellData = [
            'nickname' => '',
            'mobile'   => '',
        ];

        if($sellMemberModel instanceof \MemberModel) {
            $sellData = [
                'nickname' => urldecode($sellMemberModel->getNick_name()),
                'mobile'   => $sellMemberModel->getMobile(),
            ];
        }

        $buyData = [
            'nickname' => $buyMemberModel instanceof \MemberModel ? urldecode($buyMemberModel->getNick_name()) : '',
            'price'    => $orderModel->getPay_price(),
        ];

        \Lib\Queue::push('wxmsg', [
            'touser'      => $buyMemberModel->getOpen_id(),
            'template_id' => \Lib\Consts::TEMP_ID_FINISH_BUY,
            'url'         => 'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $orderId . '&fund_flow=1',
            'data'        => \Lib\Wechat::getInstance()->getTmp(\Lib\Consts::TEMP_ID_FINISH_BUY, $buyData),
        ]);

        \Lib\Queue::push('wxmsg', [
            'touser'      => $sellMemberModel->getOpen_id(),
            'template_id' => \Lib\Consts::TEMP_ID_FINISH_SELL,
            'url'         => 'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $orderId . '&fund_flow=2',
            'data'        => \Lib\Wechat::getInstance()->getTmp(\Lib\Consts::TEMP_ID_FINISH_SELL, $sellData),
        ]);

        return $this->response(null);
    }

    public function orderinfoAction() {
        $request = $this->getRequest();
        $orderId = $request->get('order_id');

        if($orderId <= 0) {
            return $this->response(null, false, '50000', '无效的订单id');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return $this->response(null, false, '50000', '无效的订单id');
        }

        // 看大腿-收入
        if($orderModel->getType() === 1) {
            $uid = $orderModel->getFrom_uid();
        } else {
            return $this->response(null, false, '50000', '无效的订单类型');
        }

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return $this->response(null, false, '50000', '无效的uid');
        }

        $return['avatar'] = $memberModel->getAvatar();
        $return['price']  = $orderModel->getPrice();
        $return['time']   = $orderModel->getAdd_time();

        return $this->response($return);
    }


    /**
     * @desc 关闭订单
     *
     * @return false
     */
    public function close() {
        $orderMapper = OrderMapper::getInstance();
        $orderModels = $orderMapper->fetchAll([
            'status'        => \Lib\Consts::ORDER_STATUS_NOPAY,
            'add_time <= ?' => time() - \Lib\Consts::EXPIRE_15MINU,
        ]);

        if(empty($orderModels)) {
            return true;
        }

        $orderMapper->begin();

        $data = [
            'status'      => \Lib\Consts::ORDER_STATUS_CLOSE,
            'update_time' => time(),
        ];

        try {
            $rows = $orderMapper->update($data, [
                'status'        => \Lib\Consts::ORDER_STATUS_NOPAY,
                'add_time <= ?' => time() - \Lib\Consts::EXPIRE_15MINU,
            ]);
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            $orderMapper->rollback();
            return false;
        }

        foreach($orderModels as $orderModel) {
            if(!$orderModel instanceof \OrderModel) {
                continue;
            }

            $sparringNo      = $orderModel->getSparring_no();
            $sparringNoArr   = explode(',', $sparringNo);
            $buyDetailMapper = BuyDetailMapper::getInstance();

            $data = [
                'status'      => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
                'update_time' => time(),
            ];

            try {
                $sprRows = $buyDetailMapper->update($data, [
                    'id'     => $sparringNoArr,
                    'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
                ]);
            } catch(\Exception $e) {
                $sprRows = 0;
            }

            if($sprRows <= 0) {
                $orderMapper->rollback();
                return false;
            }
        }

        $orderMapper->commit();
        return true;
    }

    public function confirm() {
        $orderMapper = OrderMapper::getInstance();
        $orderModels = $orderMapper->fetchAll([
            'status'        => [\Lib\Consts::ORDER_STATUS_PAY, \Lib\Consts::ORDER_STATUS_REFUND_REFUSE],
            'add_time <= ?' => time() - \Lib\Consts::EXPIRE_2DAY,
        ]);

        if(empty($orderModels)) {
            return true;
        }

        foreach($orderModels as $orderModel) {
            if(!$orderModel instanceof \OrderModel) {
                continue;
            }

            \Lib\Finance::getInstance()->flow($orderModel->getFrom_uid(), \Lib\Consts::F_ORDER_INCOME,
                $orderModel->getPay_price(), function () use ($orderModel, $orderMapper) {
                    $return = \Lib\Finance::getInstance()->commission($orderModel->getFrom_uid(),
                        $orderModel->getPay_price() * \Lib\Consts::COMMISSION_RATE);

                    if(!$return) {
                        return false;
                    }

                    $isSuccess = $this->changestatus($orderModel->getId(), $orderModel->getStatus(),
                        \Lib\Consts::ORDER_STATUS_FINISH);

                    return $isSuccess;
                });
        }

        return true;
    }

}
